import {
  getProcess,
  getProductionBatchWorkOrder,
  addBatckReportWorkOrder,
  getBatchReportOrderInfo,
} from "@/api/productionManagement/reportWorkBatch.js";

export const myMethod = {
  // 排序
  sortChange(val) {},
  // 选中表格数据
  tableSelectionChange(val) {
    this.tableSelection = val;
    console.log(val);
  },
  // 切换条数
  handleSizeChange(val) {
    this.pageSize = val;
    this.currentPage = 1;
    this.getTableData();
  },
  // 切换页码
  handleCurrentChange(val) {
    this.currentPage = val;
    this.getTableData();
  },
  // 点击查询操作
  queryChange(val) {
    this.form = Object.assign(this.form, val);
    this.currentPage = 1;
    this.getTableData();
  },
  // 重置查询数据
  resetPage() {
    this.pageSize = 15;
    this.currentPage = 1;
    this.totalPage = 0;
    this.$refs.dataTableRef.tableData = [];
    this.form = {};
  },
  // 清空弹框的数据
  closeChange() {
    this.$refs.addFormRef.resetForm()
  },
  // 获取列表数据
  async getTableData() {
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const { WorkOrderCode } = this.form;
      const params = {
        BatchReportWorkOrderCode: WorkOrderCode || "", // 批量报工单编码
        rows: this.pageSize,
        page: this.currentPage,
      };
      const res = await getProductionBatchWorkOrder(params);
      if (res.status === 0) {
        this.$refs.dataTableRef.tableData = res.rows || [];
        this.totalPage = res.total || 0;
      } else {
        this.$refs.dataTableRef.tableData = [];
        this.totalPage = 0;
        this.$message.error(res.msg || "查询失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  // 获取工序数据
  async getProcessData () {
    try {
      const params = {
        page: 1,
        rows: 10000,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify([])  // 转为 JSON 字符串
      }
      const res = await getProcess(params)
      this.processOptions = res.rows || []
    } catch (err) {
        console.error('加载工序数据异常:', err)
    }
  },
  addChange() {
    this.isShowConfirmBtn = true
    this.$refs.addDialogComRef.dialogVisible = true;
    // 获取下拉框列表数据
    this.processData();
  },
  // 获取工单列表数据
  async getWorkOrderList() {
    const params = {
      WorkOrderCode: '',
      page: 1,
      rows: 10000,
    }
    const query = new URLSearchParams(params).toString();
    const url = `api/ProductionWorkOrder/getPageDate?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取生产人员
  async getInspectorsList() {
    const params ={
      page: 1,
      rows: 1000,
      sort: 'CreateDate',
      order: 'desc',
      wheres: JSON.stringify([])
    }
    const url = `/api/Employees/getPageData`;
    return this.http
      .post(url, params, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取不良品项列表
  async getDefectItemList() {
    const params ={
      page: 1,
      rows: 10000,
      sort: 'CreateDate',
      order: 'desc',
      defectItemCode: ''
    }
    const query = new URLSearchParams(params).toString();
    const url = `api/DefectItem/getPageData?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取班组列表
  async getTeamList() {
    const params ={
      page: 1,
      rows: 10000,
      sort: 'CreateDate',
      order: 'desc',
      TeamName: "", // 班组名称
    }
    const query = new URLSearchParams(params).toString();
    const url = `api/Team/GetTeamInfoList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取设备列表
  async getVendList() {
    const params ={
      page: 1,
      rows: 10000,
      sort: 'CreateDate',
      order: 'desc',
      VendName: "", // 设备名称
    }
    const query = new URLSearchParams(params).toString();
    const url = `api/Vend/GetVendInfoList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  async processData() {
    this.$refs.addDialogComRef.loading = true;
    try {
      const [data1, data2, data3, data4, data5] = await Promise.all([
        this.getWorkOrderList(),
        this.getInspectorsList(),
        this.getDefectItemList(),
        this.getTeamList(),
        this.getVendList()
      ]);
      this.$refs.addFormRef.tableData = data1 ? JSON.parse(JSON.stringify(data1)) : [];
      this.$refs.addFormRef.employeeOption = data2 ? JSON.parse(JSON.stringify(data2)) : [];
      this.$refs.addFormRef.defectItemOption = data3 ? JSON.parse(JSON.stringify(data3)) : [];
      this.$refs.addFormRef.teamOptions = data4 ? JSON.parse(JSON.stringify(data4)) : [];
      this.$refs.addFormRef.equipmentOptions = data5 ? JSON.parse(JSON.stringify(data5)) : [];
      this.$refs.addDialogComRef.loading = false;
    } catch (error) {
      this.$refs.addDialogComRef.loading = false;
      console.error("获取数据失败:", error);
    }
  },
  // 确认提交操作
  confirmChange() {
    this.$refs.addFormRef.confirmChange();
  },
  async okChange() {
    console.log('通过校验');
    try {
        this.$refs.addDialogComRef.loading = true;
        const params = {
          "batchReportDate": this.$refs.addFormRef.reportTime || '', // 报工日期
          "batchReportWorkOrderDetails": this.$refs.addFormRef.addReportWorkBatchList.map(item=>{
            return {
              "workOrder_Id": item.workOrder_Id, // 工单Id
              "process_Id": item.process_Id, // 工序Id
              "inventory_Id": item.inventory_Id, // 存货id
              "reportQty": item.reportQty, // 报工数
              "goodQty": item.goodQty, // 良品数
              "noGoodQty": item.noGoodQty, // 不良品数
              "startDate": item.startDateDay + ' ' + item.startDateTime + ':00', // 开始时间
              "endDate": item.endDateDay + ' ' + item.endDateTime + ':00', // 结束时间
              "reoportDurationHour": item.reoportDurationHour, // 报工时长
              "reoportDurationMinute": item.reoportDurationMinute, // 报工时长
              "productUserId": item.inspectionId, // 生产人员Id
              "sort": item.sort, // 工序名称对应的排序
              "teamId": item.teamId, // 班组id
              "vendId": item.vendId,// 设备id
              "defectItems": item.noGoodQty ? [
                {
                  "defectItemId": item.defectItemId, // 不良项Id
                  "qty": item.noGoodQty, //数量
                }
              ] : []
            }
          })
        }
        const text = "添加"
        const result = await addBatckReportWorkOrder(params);
        if (result.ok) {
          this.$message.success(text + "成功");
          this.$refs.addDialogComRef.dialogVisible = false;
          this.currentPage = 1;
          this.closeChange();
          this.getTableData();
        } else {
          this.$message.error(
              (result.err && result.err.msg) || text + "失败"
          );
        }
        this.$refs.addDialogComRef.loading = false;
    } catch (err) {
        this.$refs.addDialogComRef.loading = false;
        console.error("数据异常:", err);
    }
  },
  async detailChange(val) {
    this.isShowConfirmBtn = false
    this.$refs.detailDialogComRef.dialogVisible = true;
    // 获取详情数据
    try{
      const result = await getBatchReportOrderInfo({ batchReportCode: val.batchReportCode});
      if (result.ok && result.data) {
        console.log('详情：', result.data.batchReportWorkOrderInfoLists);
        this.detailInfo.batchReportDate = result.data.batchReportDate || ''
        this.detailInfo.batchReportWorkOrderInfoLists = result.data.batchReportWorkOrderInfoLists &&result.data.batchReportWorkOrderInfoLists.length>0 ? result.data.batchReportWorkOrderInfoLists: []
        this.$refs.detailDataTableRef.tableData = this.detailInfo.batchReportWorkOrderInfoLists
      } else {
        this.$message.error(
            (result.err && result.err.msg) || text + "失败"
        );
      }
    } catch (err) {
      console.error("数据异常:", err);
    }
  },
  closeDetailChange() {
    this.detailInfo = {}
    this.$refs.detailDialogComRef.dialogVisible = false;
  }
};
